package cn.kgc.service.impl;

import cn.kgc.common.dtoutils.dtoUtil;
import cn.kgc.config.WXPayConstants;
import cn.kgc.config.WXPayRequest;
import cn.kgc.config.WXPayUtil;
import cn.kgc.dao.mapper.ItripHotelOrderMapper;
import cn.kgc.dao.mapper.ItripHotelTempStoreMapper;
import cn.kgc.dao.mapper.ItripTradeEndsMapper;
import cn.kgc.dtos.Dto;
import cn.kgc.pojo.ItripHotelOrder;
import cn.kgc.pojo.ItripHotelTempStore;
import cn.kgc.service.ItripHotelOrderPayService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ItripHotelOrdePayrServiceimpl implements ItripHotelOrderPayService {

    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;

    @Resource
    private ItripTradeEndsMapper itripTradeEndsMapper;
    @Resource
    private ItripHotelTempStoreMapper itripHotelTempStoreMapper;


    /**
     * 用户支付返回网址页面生成二维码
     * @param orderNo 订单编号
     * @return 网址
     */
    @Override
    public Dto updateOrderByorderNo(String orderNo) {
        try {
            ItripHotelOrder itripHotelOrder= itripHotelOrderMapper.selectOrderByorderNo(orderNo);
            if (itripHotelOrder!=null){
                Map<String,String> map=new HashMap<String,String>();
                //公众账号ID
                map.put("appid","wxab8acb865bb1637e");
                //商户号
                map.put("mch_id","11473623");
                //随机字符串
                map.put("nonce_str",WXPayUtil.generateNonceStr());
                //商品描述
                map.put("body","付款中心-订单付款");
                //商户订单号
                map.put("out_trade_no",itripHotelOrder.getOrderNo());
                //商品id
                map.put("product_id", itripHotelOrder.getId()+"");
                //标价金额
                map.put("total_fee","1");
                //终端IP
                map.put("spbill_create_ip","123.12.12.123");
                //签名类型
                map.put("sign_type","HMAC-SHA256");
                //通知地址
                map.put("notify_url","http://q5jizd.natappfree.cc/trade/api/jieguo");
                //交易类型
                map.put("trade_type","NATIVE");
                //货币类型
                map.put("fee_type", "CNY");
                //签名
                map.put("sign",WXPayUtil.generateSignature(map,"2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.HMACSHA256));
                // map变成xml 字符串
                String xml= WXPayUtil.mapToXml(map);
                //发送数据给微信息,获取结果xml
                String url="https://api.mch.weixin.qq.com/pay/unifiedorder";
                //微信返回的数据
                String result=WXPayRequest.sendMessageToWx(url,xml);
                //转为map集合
                Map<String,String> resultMap=  WXPayUtil.xmlToMap(result);
                //FAIL
                String  s= resultMap.get("err_code");
                if (s!=null&&s.equals("INVALID_REQUEST")){
                    return dtoUtil.getDto("2222","订单重复", null,"false",null);
                }
                if (s!=null&&s.equals("ORDERPAID")){
                    return dtoUtil.getDto("2222","订单已支付", null,"false",null);
                }
                //String WXURL= getUrl(result);
                //System.out.println(WXURL);
                // 4 将二维码的地址给前端  ,由前端生成二维码图片 code_url
                Map<String,String> map1=new HashMap<String,String>();
                map1.put("codeUrl",resultMap.get("code_url"));
                map1.put("payAmount",itripHotelOrder.getPayAmount()+"");
                return dtoUtil.getDto("0000","跳转微信支付成功", map1,"true",null);
            }else{
                return dtoUtil.getDto("1111","订单信息没有", null,"false",null);
            }
        }catch (Exception e){
            System.out.println(e);
            return dtoUtil.getDto("2222","支付异常", null,"false",e);
        }
    }

    /**
     * 微信回调函数
     * @param xmlResult
     * @return
     */
    @Override
    public boolean huidiao(String xmlResult) {

        try{
            //微信返回的数据
            Map<String,String> result= WXPayUtil.xmlToMap(xmlResult);
            if(result.get("result_code").equals("SUCCESS")&&result.get("return_code").equals("SUCCESS")){
                //out_trade_no
                ItripHotelOrder itripHotelOrder= itripHotelOrderMapper.selectOrderByorderNo(result.get("out_trade_no"));
                long hotelId=itripHotelOrder.getHotelId();
                long roomId=itripHotelOrder.getRoomId();
                if (itripHotelOrder!=null){
                    //数据库增加一条消费信息信息
                    System.out.println(result.get("out_trade_no"));
                    itripTradeEndsMapper.insert(result.get("out_trade_no"));
                    System.out.println("123456");
                    //查询库存表是否已有数据
                    List<ItripHotelTempStore> list = itripHotelTempStoreMapper.selectByPrimaryKey(hotelId,roomId);
                    System.out.println("123");
                    //构建数据
                    ItripHotelTempStore itripHotelTempStore1=new ItripHotelTempStore();
                    itripHotelTempStore1.setHotelId(hotelId);
                    itripHotelTempStore1.setRoomId(roomId);
                    int num=0;
                    //判断库存表是否已有数据
                    if (list.size()==0){
                        itripHotelTempStore1.setStore(20);
                        itripHotelTempStore1.setRecordDate(new Date());
                        itripHotelTempStore1.setCreationDate(new Date());
                        //没有  增加一条数据
                        num=itripHotelTempStoreMapper.insert(itripHotelTempStore1);
                        System.out.println("111");
                    }else{
                        itripHotelTempStore1.setStore(list.get(0).getStore());
                        //构建数据
                        itripHotelTempStore1.setCreationDate(list.get(0).getCreationDate());
                        //没有  增加一条数据
                        itripHotelTempStore1.setRecordDate(new Date());
                        num=itripHotelTempStoreMapper.insert(itripHotelTempStore1);
                        System.out.println(222);
                    }
                    if (num>0){
                      /*  //修改库存数量
                        itripHotelTempStoreMapper.updatestoreByid(hotelId,roomId,itripHotelOrder.getCount());*/
                        //修改订单状态
                        itripHotelOrderMapper.updateByPrimaryKey(result.get("out_trade_no"));
                        System.out.println(333);
                        return true;
                    }else {
                        return false;
                    }
                }
                return false;
            }else{
                System.out.println(result.get("err_code_des"));
                return  false;
            }

        }catch (Exception e){
            return false;
        }

    }

    /**
     * 页面响应方法
     * @param orderNo
     * @return
     */
    @Override
    public Dto RenderResponse(String orderNo) {
        try {
            ItripHotelOrder itripHotelOrder=  itripHotelOrderMapper.selectOrderByorderNo(orderNo);
            if (itripHotelOrder!=null){
                return  dtoUtil.getDto("3333","正常响应", itripHotelOrder,"true",null);
            }else{
                return dtoUtil.getDto("4444","没有该订单", null,"false",null);
            }

        }catch (Exception e){
            System.out.println(e);
            return dtoUtil.getDto("5555","页面响应异常", null,"false",e);
        }
    }
}
